package com.example.news.ui;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.news.MainActivity;
import com.example.news.R;
import com.example.news.activity.LoginActivity;
import com.example.news.bean.UserInfo;
import com.example.news.helper.UserManage;
import com.example.news.helper.gethttp;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserFragment extends Fragment {
    public View vi;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public UserFragment() {

    }
    // TODO: Rename and change types and number of parameters
    public static UserFragment newInstance(String param1, String param2) {
        UserFragment fragment = new UserFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }
    public String ip;
    Handler loginhandler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {
                    try {
                        JSONObject pbj=new JSONObject(msg.obj.toString());
                        if(pbj.getString("loginresult").equals("登录成功")){
                            JSONObject user=new JSONObject(pbj.getString("User"));
                            Log.i("User:",user.getString("readcount"));
                            UserManage.getInstance().deleteuser(getContext());
                            UserManage.getInstance().saveUserInfo(getContext(),user.getString("userid"),user.getString("userpasswd"),user.getString("Createtime"),user.getInt("readcount"),user.getString("habbit"));
//                            UserManage.getInstance().savehabbit(getContext(),user.getString("habbit"));
                            setunerinfo();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                case 2 :break;
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        vi=view;
        ip=getActivity().getString(R.string.ip);
        UserInfo user= UserManage.getInstance().getUserInfo(getContext());
        String url="http://"+ip+":8080/user/login?userId="+user.getUserName()+"&userPasswd="+user.getUserName();
        gethttp ghttp=new gethttp(url,loginhandler);
        ghttp.start();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    public void setunerinfo()
    {
        TextView userid=vi.findViewById(R.id.userid);
        TextView createtime=vi.findViewById(R.id.createtime);
        TextView readcount=vi.findViewById(R.id.readcount);
        TextView like=vi.findViewById(R.id.like);
        UserInfo user= UserManage.getInstance().getUserInfo(getContext());
        Log.i(TAG, "setunerinfo: "+user.toString());
        userid.setText("用户名："+user.getUserName());
        createtime.setText("创建时间："+user.getCreatetime());
        readcount.setText("阅读新闻数："+user.getreadcount());
        like.setText("喜好："+user.getHabbit());
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {

            }
        };
    }
    private float lastTouchX;
    private float lastTouchY;
    // 实现回调接口，定义触摸后的操作
    private MainActivity.MyTouchListener myTouchListener = new MainActivity.MyTouchListener() {

        @Override
        public void onTouch(MotionEvent ev) {
            switch (ev.getAction()) {
                // 手指点击屏幕时，记录当前的X坐标和Y坐标
                case MotionEvent.ACTION_DOWN:
                    lastTouchX = ev.getX();
                    lastTouchY = ev.getY();
                    break;
                /*
                 * 手指在屏幕上滑动的时候，获取当前的X坐标和Y坐标，然后和起始位置的坐标做对比，
                 * 如果移动的距离超过1，显示该图片
                 */
                case MotionEvent.ACTION_MOVE:
                    float disX = ev.getX() - lastTouchX;
                    float disY = ev.getY() - lastTouchY;
                    Log.i(TAG, "onTouch: Y="+disY);
                    Log.i(TAG, "onTouch: X="+disX);
                    if (disX <- 400) {

                    }else if(disX >400){
                        NavController controller = Navigation.findNavController(getActivity(),R.id.nav_host_fragment_activity_main);
                        controller.navigate(R.id.action_userFragment_to_homeFragment);
                    }else if(disY>350){

                    }else if(disY <-350){

                    }

                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        // 在onResume里面注册回调
        ((MainActivity) this.getActivity())
                .registerMyTouchListener(myTouchListener);
    }
    public void tos(String line)
    {
        Toast.makeText(getContext(), line, Toast.LENGTH_SHORT).show();
    }
}